<template>
  <view class="chat-page">
    <!-- 聊天列表 -->
    <ChatList
      @redPacketClick="getPay"
      :isSafeArea="true"
      @retryClick="retryClick"
      :showIsRead="showIsRead"
      @leftAvatarClick="leftAvatarClick"
      @rightAvatarClick="rightAvatarClick"
      :bottomMenu="chatBottomMenu"
      :inputValue="inputValue"
      @menuClick="chatMenuClick"
      ref="chatList"
      :finish="finish"
      @loadmore="loadmore"
      @sendMessage="sendMessage"
      :list="listData"
      :loadingStatus="loadingStatus"
    >
    </ChatList>
    <OrderList
      v-show="orderdialogShow"
      @orderdialogChange="orderdialogChange"
      @chooseOrder="chooseOrder"
    >
    </OrderList>
    <OrderList2
      v-show="orderdialogShow2"
      @shorderdialogChange="shorderdialogChange"
      @shchooseOrder="shchooseOrder"
    >
    </OrderList2>
    <GoodList
      v-show="gooddialogShow"
      @gooddialogChange="gooddialogChange"
      @chooseGood="chooseGood"
    >
    </GoodList>
  </view>
</template>

<script>
import ChatList from "../components/chat-list/chat-list.vue";
import OrderList from "../components/order-list/order-list.vue";
import OrderList2 from "../components/order-list/order-list2.vue";
import GoodList from "../components/good-list/good-list.vue";
import { formatGetMessage, formatSendMessage } from "./messageCovert.js";
var app = getApp();
export default {
  components: {
    ChatList,
    OrderList,
    OrderList2,
    GoodList,
  },
  data() {
    return {
      type: 0, //发送的对象类型
      id: null, // 聊天对象id
      headimg: "", // 聊天对象头像
      listData: [],
      orderdialogShow: false,
      orderdialogShow2: false,
      gooddialogShow: false,
      showIsRead: false, //是否显示未读
      finish: false,
      loadingStatus: "more", //more,loading,noMore
      inputValue: "",
      isCompleted: false,
      chatBottomMenu: [],
      page: 1,
      limit: 10,
      nomore: false,
      canload: true,
    };
  },

  onLoad(opt) {
    // return;
    this.id = opt.id;
    this.type = opt.type;
    if (this.type == 1) {
      this.chatBottomMenu = [
        {
          name: "订单",
          img: "../../../static/img/chat/order.png",
          type: 4,
        },
        {
          name: "售后订单",
          img: "../../../static/img/chat/order2.png",
          type: 6,
        },
        {
          name: "商品",
          img: "../../../static/img/chat/goods.png",
          type: 5,
        },
      ];
    }
    this.headimg = opt.headimg;
    this.getlist();
    if (opt.name) {
      uni.setNavigationBarTitle({
        title: opt.name,
      });
    }
    // uni.$off("socketMessage-api");
    uni.$on("socketMessage-api", this.handleSocket);
    // uni.$on("toChat", this.getChatData);
  },

  beforeDestroy() {
    uni.$off("socketMessage-api", this.handleSocket);
    // uni.$off("toChat", this.getChatData);
  },

  created() {
    // this.getDataTest();
  },

  methods: {
    getPay() {},

    //获取记录
    getlist() {
      app.showLoading("加载中...");
      if (this.type == 4) {
        app.sendSocketMessage({
          session_id: app.globalData.kefuInfo.id,
          type: "api",
          api_path: "Chat/gethistory",
          to_mid: this.id,
          page: this.page,
          limit: this.limit,
          random_str: app.globalData.kefuInfo.random_str
            ? app.globalData.kefuInfo.random_str
            : null,
        });
      } else if (this.type == 1) {
        //区别系统消息
        app.sendSocketMessage({
          type: "api",
          api_path: "Chat/gethistory",
          to_admin_user_id: this.id,
          page: this.page,
          limit: this.limit,
        });
      } else {
        app.sendSocketMessage({
          type: "api",
          api_path: "Chat/gethistory",
          to_mid: this.id,
          page: this.page,
          limit: this.limit,
        });
      }
    },

    //处理ws消息
    handleSocket(data) {
      var that = this;
      //   that.loaded();
      if (data.api_path == "Chat/gethistory") {
        console.log("gethistory", data.data);
        if (data.data && data.data.length > 0) {
          data.data.forEach((item) => {
            that.listData.unshift(formatGetMessage(item, that.headimg));
          });
          console.log(that.listData);
          if (that.page == 1) {
            if (data.data.length < 10) {
              that.loadingStatus = "nomore";
              that.finish = true;
            }
            setTimeout(() => {
              uni.$emit("sendMessagetoBottom");
              app.showLoading(false);
              //console.log("加载关闭1", that.page, this.id);
            }, 500);
          } else {
            that.loadingStatus = "more";
            setTimeout(() => {
              app.showLoading(false);
              //console.log("加载关闭2", that.page, this.id);
            }, 1000);
          }
        } else {
          that.loadingStatus = "nomore";
          if (that.page == 1) {
            that.finish = true;
          }
        }
        // if (data.data && data.data.length > 0) {
        //   this.listData = this.listData.concat(data.data);
        // } else {
        //   this.nomore = true;
        //   this.canload = false;
        // }
      }

      //获取实时信息  判断type 是 数字类型
      if (!isNaN(data.type) && !isNaN(parseFloat(data.type))) {
        console.log("实时信息type", data.type);
        if (this.type == 1) {
          if (this.id == data.admin_user_id) {
            this.listData.push(formatGetMessage(data, this.headimg));
            this.setSrollToBottom();
            app.sendSocketMessage({
              type: "api",
              api_path: "Chat/clearnotread",
              admin_user_id: this.id,
            });
          }
        } else {
          if (this.id == data.mid) {
            this.listData.push(formatGetMessage(data, this.headimg));
            this.setSrollToBottom();
            app.sendSocketMessage({
              type: "api",
              api_path: "Chat/clearnotread",
              mid: this.id,
            });
          }
        }
      }

      //获取发送消息回执
      if (data.type == "my_send") {
        console.log("my_send", data.message);

        let item = null;
        if (data.message.msg_type == 5) {
          //特殊消息类型用特殊id判断
          for (let i = this.listData.length - 1; i >= 0; i--) {
            if (this.listData[i].content == data.message.data_args.name) {
              item = this.listData[i];
              break;
            }
          }
        } else if (data.message.msg_type == 16) {
          for (let i = this.listData.length - 1; i >= 0; i--) {
            if (this.listData[i].content == data.message.data_id) {
              item = this.listData[i];
              break;
            }
          }
        } else {
          for (let i = this.listData.length - 1; i >= 0; i--) {
            if (this.listData[i].content === data.message.content) {
              item = this.listData[i];
              break;
            }
          }
        }
        if (item) {
          item.loading = false;
        }
      }
    },

    getChatData(data) {
      if (data) {
        if (data.type == "product") {
          setTimeout(() => {
            console.log("product", data);
            uni.$emit("getProduct", data);
          }, 300);
        }
      }
    },

    // 加载更多
    loadmore() {
      console.log("加载更多");
      if (this.loadingStatus == "nomore") {
        return;
      }
      this.loadingStatus = "loading";
      setTimeout(() => {
        this.page++;
        this.limit = 7;
        this.getlist();
      }, 100);
      //模拟加载更多
      //   setTimeout(() => {
      //     this.getMoreTestData();
      //     console.log(this.page);
      //     if (this.page >= 3) {
      //       this.finish = true;
      //       this.loadingStatus = "nomore";
      //     }
      //     this.page++;
      //   }, 100);
    },

    // 消息重发
    retryClick(item) {
      console.log("消息重发", item);
      const index = this.listData.findIndex((i) => i.id === item.id);
      if (index > -1) {
        console.log("找到的索引位置：", index);
        this.listData.splice(index, 1); // 从找到的索引位置删除1个元素
        this.$forceUpdate();
        this.sendMessage({
          type: item.type,
          content: item.content,
          extend: item.extend,
        });
      }
    },

    // 左测消息，头像点击
    leftAvatarClick(item) {
      console.log("左测消息，头像点击");
      console.log(item);
    },

    // 右测消息，头像点击
    rightAvatarClick(item) {
      console.log("右测消息，头像点击事件");
      console.log(item);
    },

    // 菜单点击
    chatMenuClick(item) {
      let that = this;
      that.setSrollToBottom();
      if (item) {
        console.log("chatMenuClick", item);
        if (item.type === 1) {
          app.chooseImage(function (urls) {
            for (var i = 0; i < urls.length; i++) {
              that.sendMessage({
                type: "image",
                content: urls[i],
                extend: null,
              });
            }
          }, 9);
        }
        if (item.type === 2) {
          app.chooseAlbumVideo(
            function (urls) {
              for (var i = 0; i < urls.length; i++) {
                console.log("视频上传链接：", urls[i].url);
                that.sendMessage({
                  type: "video",
                  content: urls[i].url,
                  extend: {
                    cover: urls[i].extend.video_image,
                  },
                });
              }
            },
            9,
            30
          );
        }
        if (item.type === 3) {
          app.chooseVideo(
            function (urls) {
              for (var i = 0; i < urls.length; i++) {
                console.log("视频上传链接：", urls[i].url);
                that.sendMessage({
                  type: "video",
                  content: urls[i].url,
                  extend: {
                    cover: urls[i].extend.video_image,
                  },
                });
              }
            },
            9,
            30
          );
        }
        if (item.type === 4) {
          that.orderdialogShow = true;
        }
        if (item.type === 6) {
          that.orderdialogShow2 = true;
        }
        if (item.type === 5) {
          that.gooddialogShow = true;
        }
      }
    },

    // 发送消息
    sendMessage({ type, content, extend }) {
      let id = Math.random()
        .toString(36)
        .substring(2, 2 + 8);

      this.listData.push({
        time: new Date().valueOf() / 1000,
        showTime: true,
        id,
        type, //消息类型
        right: true, //输出方
        content, //消息内容
        extend, //消息扩展内容（对象自定义消息类型所需的额外内容）
        loading: true,
        avatar:
          this.type == 4
            ? app.globalData.kefuInfo.headimg
            : app.globalData.memberinfo.headimg,
      });

      app.sendSocketMessage(
        formatSendMessage(this.type, this.id, type, content, extend)
      );

      this.setSrollToBottom();

      setTimeout(() => {
        let item = this.listData.find((item) => item.id === id);

        if (item && item.loading) {
          item.loading = false;
          item.isError = true;
        }
      }, 10000);

      //模拟发送成功状态
      //   setTimeout(() => {
      //     let item = this.listData.find((item) => item.id === id);

      //     if (item) {
      //       item.loading = false;
      //     }
      //   }, 4000);
    },

    //滚动到底部
    setSrollToBottom() {
      uni.$emit("sendMessagetoBottom");
      setTimeout(() => {
        uni.$emit("sendMessagetoBottom");
      }, 500);
    },

    getDataTest() {
      app.showLoading("加载中...");
      let data = [
        {
          time: new Date().valueOf() / 1000,
          id: 666,
          content: "新佣金到账通知",
          type: "template",
          extend: {
            detail:
              "变动类型:消费 变动金额:-1080 当前余额:99746437.25 时间2025-04-25 09:58",
            data_args: [
              "订单号:250422155237136744",
              "获得佣金:19.90",
              "来源用户:123",
              "累计佣金100015.45",
              "点击查看佣金明细",
            ],
            data_id: 506,
            msg_type: 14,
          },
          right: false,
          isRead: true,
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 666,
          content:
            "悦黔水牛奶 甄选意大利地中海水牛 甘蔗菠萝喂养 0添加 配料只有生水牛乳和生牛乳",
          type: "product",
          extend: {
            pic: "https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250122/b2225f8e1b80fe302b1f0ee3365e7189.jpg",
            proid: 561,
            sell_price: 110,
          },
          right: true,
          isRead: true,
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 6666,
          content:
            "每天一点心理学【鸭子定律每天一点心理学【鸭子定律每天一点心理学【鸭子定律每天一点心理学【鸭子定律",
          type: "share",
          extend: {
            pic: "https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250122/b2225f8e1b80fe302b1f0ee3365e7189.jpg",
            shareid: 561,
            admin_img:
              "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
            admin_name:
              "每天一点心理学每天一点心理学每天一点心理学每天一点心理学每天一点心理学",
          },
          right: true,
          isRead: true,
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 2,
          content: "你好",
          type: "text",
          right: true,
          isRead: true,
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 22,
          content: "你好111",
          type: "text",
          right: false,
          isRead: false,
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 222,
          content:
            "你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111你好111",
          type: "text",
          right: true,
          isError: true,
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 3,
          right: true,
          content:
            "https://hedashepin.oss-cn-guangzhou.aliyuncs.com/upload/3/20250126/fcf59458af13a934059eb284fd1ea7ed.png",
          type: "image",
          isError: true,
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 31,
          right: false,
          content:
            "https://hedashepin.oss-cn-guangzhou.aliyuncs.com/upload/3/20250303/580b99d3b2741f3d39468a5f9bd3e192.png",
          type: "image",
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 1,
          content: "我照片靓不靓",
          type: "text",
          right: false,
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/125b546a3cc2468e8a9fc4a8b9e6336a!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 1,
          content: "http://www.w3school.com.cn/example/html5/mov_bbb.mp4",
          type: "video",
          right: true,
          isError: true,
          extend: {
            cover:
              "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
          },
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 1,
          content: "http://www.w3school.com.cn/example/html5/mov_bbb.mp4",
          type: "video",
          right: false,
          extend: {
            cover:
              "https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250109/7b0123517d76738101ff42a12a381d0a.jpg",
          },
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        {
          time: new Date().valueOf() / 1000,
          id: 99,
          content: "",
          type: "order",
          right: true,
          extend: {
            orderid: 560,
            ordernum: 250329100140917798,
            prolist: [
              {
                proid: 560,
                pic: "https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250109/7b0123517d76738101ff42a12a381d0a.jpg",
                sell_price: "88",
                name: "商品名字商品名字商品名字商品名字商品名字商品名字",
                num: "1",
              },
              {
                pic: "https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250109/7b0123517d76738101ff42a12a381d0a.jpg",
                sell_price: "800",
                name: "商品名字商品名字商品名字商品名字商品名字商品名字",
                num: "3",
              },
            ],
          },
          avatar:
            "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
        },
        //未启用消息类型
        // {
        // 	time: new Date().valueOf() / 1000,
        // 	id: 1,
        // 	content: '张三',
        // 	type: 'red-packet',
        // 	right: true,
        // 	amount: 55.6,
        // 	avatar: 'https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg'
        // },
        // {
        // 	time: new Date().valueOf() / 1000,
        // 	id: 1,
        // 	content: 'http://www.w3school.com.cn/example/html5/mov_bbb.mp4',
        // 	type: 'sound',
        // 	right: true,
        // 	extend: {
        // 		duration: 6,
        // 	},
        // 	avatar: 'https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg'
        // },
      ];

      data.forEach((item) => {
        this.listData.unshift(item);
        item.showTime = true;
      });

      setTimeout(() => {
        uni.$emit("sendMessagetoBottom");
        app.showLoading(false);
      }, 500);
    },

    getMoreTestData() {
      this.listData.unshift({
        time: new Date().valueOf() / 1000,
        id: 2,
        content: "你好",
        type: "text",
        right: true,
        avatar:
          "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
      });
      this.listData.unshift({
        time: new Date().valueOf() / 1000,
        id: 2,
        content: "你好2222",
        type: "text",
        right: false,
        avatar:
          "https://img2.woyaogexing.com/2021/07/03/37bd35bb2a8a4f0c8af170e9e6abb7fd!400x400.jpeg",
      });
      uni.$emit("scrollerMore");
      this.loadingStatus = "more";
    },

    orderdialogChange: function (e) {
      const productId = e;
      this.orderdialogShow = !this.orderdialogShow;
    },

    chooseOrder: function (e) {
      console.log("选择订单：", e);
      this.orderdialogShow = !this.orderdialogShow;
      this.sendMessage({
        type: "order",
        content: e.id,
        extend: {
          etype: 0,
          orderid: e.id,
          ordernum: e.ordernum,
          price: e.product_price,
          prolist: e.prolist,
          status: e.status,
          freight_type: e.freight_type,
        },
      });
    },

    shorderdialogChange: function (e) {
      const productId = e;
      this.orderdialogShow2 = !this.orderdialogShow2;
    },

    shchooseOrder: function (e) {
      console.log("选择售后订单：", e);
      this.orderdialogShow2 = !this.orderdialogShow2;
      this.sendMessage({
        type: "order",
        content: e.orderid,
        extend: {
          etype: 1,
          orderid: e.orderid,
          refund_id: e.id,
          ordernum: e.ordernum,
          price: e.product_price,
          prolist: e.prolist,
          refund_status: e.refund_status,
          freight_type: e.freight_type,
        },
      });
    },

    gooddialogChange: function (e) {
      this.gooddialogShow = !this.gooddialogShow;
    },

    chooseGood: function (e) {
      console.log("选择商品：", e);
      this.gooddialogShow = !this.gooddialogShow;
      this.sendMessage({
        type: "product",
        content: e.name,
        extend: {
          pic: e.pic,
          sell_price: e.sell_price,
          proid: e.id,
          ptype: "shop",
        },
      });
    },
  },
};
</script>

<style lang="scss">
.chat-page {
  display: flex;
  flex: 1;
}
</style>
